//
//  WYHomeHeaderController.m
//  CirclePush
//
//  Created by admin on 2018/4/13.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYHomeHeaderController.h"
#import "WYHomeCollectionCell.h"
#import "WYTAdvertisementCell.h"
#import "WYMediaCell.h"
#import "WYPromptCell.h"
@interface WYHomeHeaderController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,SDCycleScrollViewDelegate,WYTAdvertisementCellDelegate>

@property (nonatomic, strong)SDCycleScrollView *advView;
@property (nonatomic,strong) WYImageModel *imageMedel;
@property (nonatomic,strong)NSMutableDictionary *heightDict;
@property (nonatomic,strong)NSMutableDictionary *dicHeight;
@property (nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation WYHomeHeaderController
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
-(NSMutableDictionary *)dicHeight
{
    if (!_dicHeight) {
        _dicHeight = [[NSMutableDictionary alloc]init];
    }
    return _dicHeight;
}
-(NSMutableDictionary *)heightDict
{
    if (!_heightDict) {
        _heightDict = [[NSMutableDictionary alloc]init];
    }
    return _heightDict;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadImage];
  //  self.view.backgroundColor = [UIColor redColor];
//    if (@available(iOS 11.0, *)){
//        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
//    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCellHeight:) name:@"editCollectionViewHeight" object:nil];
    [self loadData];
    
}
-(void)loadData
{
    WEAKSELF
    [WYHttpServer getHotList:@"hotMedia" SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        
        if (success) {
            weakSelf.dataArray = [[NSMutableArray alloc]initWithArray:response[@"result"]];
            [weakSelf.tableView reloadData];
            
        }
        
        
        
    }];
    
    
    
    
    
    
}

-(void)changeCellHeight:(NSNotification *)notification
{
     self.dicHeight[@"height"]=notification.object[@"key"];
    [self.tableView beginUpdates];
    NSIndexPath *index= [NSIndexPath indexPathForRow:2 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:(UITableViewRowAnimationNone)];
    [self.tableView endUpdates];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"testChangeHeight" object:nil userInfo:self.dicHeight];
    
    
    //self.tableView.frame = self.view.frame;
    
}

-(void)setTest:(NSString *)test
{
    _test = test;
    self.tableView.frame = self.view.frame;
//    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.bottom.top.mas_equalTo(0);
//    }];
}



-(void)loadImage
{
    WEAKSELF
    [WYHttpServer getImageListWithtType:@"2" SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            NSArray *array = [WYImageModel getImageModelFromJson:response[@"result"]];
            if (array.count) {
                weakSelf.imageMedel = array[0];
                [weakSelf.tableView reloadData];
            }
        }
    }];
}


-(void)setupUI
{
    self.tableView = [[WYTableView alloc]init];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.mas_equalTo(0);
    }];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYHomeCollectionCell" bundle:nil] forCellReuseIdentifier:@"WYHomeCollectionCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYTAdvertisementCell" bundle:nil] forCellReuseIdentifier:@"WYTAdvertisementCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"WYMediaCell" bundle:nil] forCellReuseIdentifier:@"WYMediaCell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"homeCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYPromptCell" bundle:nil] forCellReuseIdentifier:@"WYPromptCell"];
   // [self.tableView registerClass:[WYHomeRecommendCell class] forCellReuseIdentifier:@"WYHomeRecommendCell"];
 //   self.tableView.backgroundColor = [UIColor redColor];
    self.tableView.bounces = NO;
    self.tableView.tableFooterView = [[UIView alloc]init];
  //  self.view.backgroundColor = [UIColor blueColor];
}

#pragma mark - tableview delegate / dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        WYHomeCollectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYHomeCollectionCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"WYHomeCollectionCell" owner:nil options:nil].firstObject;
        }
        cell.collectionView.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    if (indexPath.row==1) {
        WYTAdvertisementCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYTAdvertisementCell" forIndexPath:indexPath];
        if (self.imageMedel) {
          //  [cell setImageModel:self.imageMedel];
            NSString *url = self.imageMedel.image;
        
        [cell.adImageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image.size.height) {
                /**  < 图片宽度 >  */
                CGFloat imageW = [UIScreen mainScreen].bounds.size.width - 2 * 8;
                /**  <根据比例 计算图片高度 >  */
                CGFloat ratio = image.size.height / image.size.width;
                /**  < 图片高度 + 间距 >  */
                CGFloat imageH = ratio * imageW + 15;
                /**  < 缓存图片高度 没有缓存则缓存 刷新indexPath >  */
                if (![[self.heightDict allKeys] containsObject:@(indexPath.row)]) {
                    [self.heightDict setObject:@(imageH) forKey:@(indexPath.row)];
                    [self.tableView beginUpdates];
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"editRowHeight" object:@{@"height":@(imageH)}];
                    
                    
                    [self.tableView endUpdates];
                }
            }
        }];
        }
        cell.delegate = self;
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    if (indexPath.row==2) {
        WYMediaCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYMediaCell" forIndexPath:indexPath];
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        //NSArray *_nameArray = @[];
        if (![self.heightDict[@"height"]stringValue].length) {
             cell.dataArray = self.dataArray;
        }
        return cell;
    }
    //    if (indexPath.row==4) {
    //        WYHomeRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYHomeRecommendCell" forIndexPath:indexPath];
    //        if (!cell) {
    //            cell = [[WYHomeRecommendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"WYHomeRecommendCell"];
    //        }
    ////        self.recommendVC = [[WYRecommendController alloc]init];
    ////        [cell.contentView addSubview:self.recommendVC.view];
    ////        self.recommendVC.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-49-[self navBarBottom]);
    //        return cell;
    //    }
    if (indexPath.row==3) {
        WYPromptCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYPromptCell" forIndexPath:indexPath];
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
    
}
-(void)clickMoblieAction
{
    [self showAlertMessage];
}
-(void)clickDeliverAction
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changeTabbarSelect" object:nil];
    
    
    //[self.tabBarController setSelectedIndex:2];
}

-(void)showAlertMessage
{
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"400-6762-9898" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = [WYMediaType getMediaLsit];
    WYMediaType *type = array[indexPath.row];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectMediaTypeName" object:@{@(indexPath.row):type}];
    //NSLog(@"%ld-----%ld",indexPath.row,indexPath.section);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 185;
    }
    if (indexPath.row==1) {
        return [[self.heightDict objectForKey:@(indexPath.row)] floatValue]+100;
    }
    if (indexPath.row==2) {
        if (self.dataArray.count) {
            return [self.dicHeight[@"height"]floatValue]+60;
        }else{
            return 0;
        }
       
    }
    
    if (indexPath.row==3) {
        return (kScreenWidth-20)/1.61+50;
    }
    return 60;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UIViewController *vc = [UIViewController new];
    vc.view.backgroundColor = [UIColor whiteColor];
    NSString *str = [NSString stringWithFormat:@"WRNavigationBar %zd",indexPath.row];
    vc.title = str;
    [self.navigationController pushViewController:vc animated:YES];
}
- (int)navBarBottom
{
    if ([WRNavigationBar isIphoneX]) {
        return 88;
    } else {
        return 64;
    }
}
@end
